// 应用入口文件

// 全局变量
let currentPage = 1;
const pageSize = 10;

// DOM元素
let loginModal, registerModal, publishQuestionModal, rechargeModal;

// 初始化函数
window.init = function() {
    // 获取模态框元素
    loginModal = document.getElementById('loginModal');
    registerModal = document.getElementById('registerModal');
    publishQuestionModal = document.getElementById('publishQuestionModal');
    rechargeModal = document.getElementById('rechargeModal');
    
    // 添加点击模态框外部关闭的事件监听
    window.onclick = handleModalClick;
    
    // 更新导航状态
    updateNavigation();
    
    // 加载首页内容
    loadContent('home');
    
    console.log('页面初始化完成');
}

// 页面加载完成后自动初始化
window.addEventListener('DOMContentLoaded', window.init);

// 加载内容页面
function loadContent(pageName) {
    const contentDiv = document.getElementById('content');
    
    // 显示加载中状态
    contentDiv.innerHTML = '<p style="text-align:center; color:#999; padding:2rem;">加载中...</p>';
    
    // 根据页面名称加载对应的HTML文件
    let htmlFile = '';
    switch(pageName) {
        case 'home':
            htmlFile = '/knowledge-qa/static/pages/home.html';
            break;
        case 'questionList':
            htmlFile = '/knowledge-qa/static/pages/question_list.html';
            break;
        case 'userInfo':
            htmlFile = '/knowledge-qa/static/pages/user_info.html';
            break;
        default:
            htmlFile = '/knowledge-qa/static/pages/home.html';
    }
    
    // 发送请求加载HTML内容
    fetch(htmlFile)
        .then(response => {
            if (!response.ok) {
                throw new Error('加载页面失败');
            }
            return response.text();
        })
        .then(html => {
            // 将加载的HTML内容设置到contentDiv中
            contentDiv.innerHTML = html;
            
            // 根据页面名称执行相应的初始化操作
            switch(pageName) {
                case 'home':
                    // 加载热门问题
                    loadFeaturedQuestions();
                    break;
                case 'questionList':
                    // 加载问题列表
                    currentPage = 1;
                    loadQuestions(currentPage);
                    break;
                case 'userInfo':
                    // 检查是否已登录
                    if (!window.currentUserId) {
                        alert('请先登录');
                        loadContent('home');
                        return;
                    }
                    
                    // 加载用户信息
                    loadUserInfo();
                    break;
            }
        })
        .catch(error => {
            console.error('加载页面失败:', error);
            contentDiv.innerHTML = '<p style="text-align:center; color:#ff4d4f; padding:2rem;">加载失败，请稍后重试</p>';
        });
}

// 页面导航函数
window.showHome = function() {
    loadContent('home');
};

window.showQuestionList = function() {
    loadContent('questionList');
};

window.showUserInfo = function() {
    if (!currentUserId) {
        alert('请先登录');
        return;
    }
    loadContent('userInfo');
};

// 更新导航状态
function updateNavigation() {
    const userInfoLink = document.getElementById('userInfoLink');
    const loginLink = document.getElementById('loginLink');
    const registerLink = document.getElementById('registerLink');
    const logoutLink = document.getElementById('logoutLink');
    
    // 检查是否有登录信息（实际项目中可能需要从localStorage或cookie中获取）
    const savedUserId = localStorage.getItem('userId');
    if (savedUserId) {
        currentUserId = savedUserId;
        userInfoLink.style.display = 'block';
        logoutLink.style.display = 'block';
        loginLink.style.display = 'none';
        registerLink.style.display = 'none';
    } else {
        userInfoLink.style.display = 'none';
        logoutLink.style.display = 'none';
        loginLink.style.display = 'block';
        registerLink.style.display = 'block';
    }
}

// 处理模态框点击事件
function handleModalClick(event) {
    if (event.target === loginModal) {
        closeLoginModal();
    } else if (event.target === registerModal) {
        closeRegisterModal();
    } else if (event.target === publishQuestionModal) {
        closePublishQuestionModal();
    } else if (event.target === rechargeModal) {
        closeRechargeModal();
    }
}

// 辅助函数：显示消息
window.showMessage = function(elementId, message, isSuccess) {
    const element = document.getElementById(elementId);
    if (element) {
        element.textContent = message;
        element.className = 'alert ' + (isSuccess ? 'alert-success' : 'alert-danger');
        element.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            element.style.display = 'none';
        }, 3000);
    }
};

// 辅助函数：格式化日期
window.formatDate = function(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
};

// 辅助函数：获取状态文本
window.getStatusText = function(status) {
    switch(status) {
        case 0: return '待解决';
        case 1: return '已解决';
        case 2: return '已关闭';
        default: return '未知';
    }
};

// 辅助函数：截断文本
window.truncateText = function(text, maxLength) {
    if (!text || text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
};

// 加载热门问题 - 支持切换悬赏排行和浏览量排行
function loadFeaturedQuestions(type = 'reward') {
    const featuredQuestionList = document.getElementById('featuredQuestionList');
    
    // 获取标签元素
    const rewardTab = document.getElementById('rewardTab');
    const viewTab = document.getElementById('viewTab');
    
    // 确保元素存在
    if (rewardTab && viewTab) {
        // 更新标签样式
        rewardTab.classList.remove('active');
        viewTab.classList.remove('active');
        
        if (type === 'reward') {
            rewardTab.classList.add('active');
        } else {
            viewTab.classList.add('active');
        }
    }
    
    // 打印调试信息
    console.log('标签类型:', type);
    console.log('悬赏标签激活状态:', rewardTab ? rewardTab.classList.contains('active') : false);
    console.log('浏览量标签激活状态:', viewTab ? viewTab.classList.contains('active') : false);
    
    // 显示加载中状态
    featuredQuestionList.innerHTML = '<p style="text-align:center; color:#999; padding:2rem;">加载中...</p>';
    
    // 选择请求的URL - 使用支持返回更多问题的接口
    const url = type === 'reward' ? '/knowledge-qa/api/question/featured?limit=10' : '/knowledge-qa/api/question/viewed-top?limit=10';
    
    // 打印请求的URL
    console.log('请求的URL:', url);
    
    // 发送请求获取热门问题
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('加载热门问题失败: HTTP ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            // 打印返回的数据，用于调试
            console.log('返回的数据:', data);
            
            if (data.success && data.questions && data.questions.length > 0) {
                const questions = data.questions;
                let html = '';
                
                questions.forEach((question, index) => {
                    // 添加排名样式
                    let rankStyle = 'position: relative;';
                    if (index === 0) rankStyle += ' background-color: #fff7e6;';
                    if (index === 1) rankStyle += ' background-color: #f0f0f0;';
                    if (index === 2) rankStyle += ' background-color: #fff0e6;';
                    
                    html += `
                        <div class="featured-question-item" style="${rankStyle}">
                            <div class="featured-question-rank">${index + 1}</div>
                            <h3 onclick="showQuestionDetail(${question.id})" class="featured-question-title">${question.title}</h3>
                            <div class="featured-question-meta">
                                <span class="featured-question-user">${question.username}</span>
                                <span class="featured-question-time">${formatDate(question.createTime)}</span>
                            </div>
                            <div class="featured-question-footer">
                                <span class="featured-question-reward">悬赏: ${question.rewardAmount}金币</span>
                                <span class="featured-question-view-count">浏览量: ${question.viewCount}</span>
                                <span class="featured-question-answer-count">回答量: ${question.answerCount}</span>
                            </div>
                        </div>
                    `;
                });
                
                featuredQuestionList.innerHTML = html;
            } else {
                featuredQuestionList.innerHTML = '<p style="text-align:center; color:#999; padding:2rem;">暂无热门问题</p>';
            }
        })
        .catch(error => {
            console.error('加载热门问题失败:', error);
            featuredQuestionList.innerHTML = '<p style="text-align:center; color:#ff4d4f; padding:2rem;">加载失败，请稍后重试</p>';
        });
}

// 页面加载完成后初始化
window.onload = init;